from django.forms import ModelForm, ModelChoiceField
from django.conf import settings
from django import forms
from django.db.models import Q

from xadmin.models import Node

siteid = settings.CN_SITEID

def node_order_tree(node_list, node_queryset):
    for node in node_queryset:
        if node.node_type == "" or node.node_type is None:
            node_list.append(node)
            s_node_set = Node.objects.filter(parent_node_id=node.id, is_active=True).filter(Q(node_type=None) | Q(node_type=''))
            node_order_tree(node_list, s_node_set)
    #print(node_list)
    return node_list


def node_list():
    node_queryset = Node.objects.filter(site_id=siteid, parent_node=None, is_active=True).filter(Q(node_type=None) | Q(node_type=''))
    node_trees = node_order_tree([], node_queryset)
    return node_trees


def get_queryset():
    order_list = node_list()
    id_list = [n.id for n in order_list]
    ordering = 'FIELD(`id`, %s)' % ','.join(str(id) for id in id_list)
    queryset = Node.objects.filter(id__in=id_list).extra(select={'ordering': ordering}, order_by=('ordering',))
    return queryset

'''
order_list = node_list()
id_list = [n.id for n in order_list]
ordering = 'FIELD(`id`, %s)' % ','.join(str(id) for id in id_list)
'''



class NodeForm(ModelForm):

    parent_node = ModelChoiceField(label='父栏目', required=False,
                                   queryset=get_queryset())
    class Meta:
        model = Node
        exclude = ('site', 'node_path', 'node_level', 'group', 'order_num')

    def __init__(self, *args, **kwargs):
        super(NodeForm, self).__init__(*args, **kwargs)
        self.fields['parent_node'].queryset = get_queryset()
        #self.fields['parent_node'].queryset = get_queryset()
        no_style_colum = ('content', 'is_active', 'is_search')
        for field_name in self.fields:
            field = self.fields[field_name]
            if field_name not in no_style_colum:
                field.widget.attrs.update({'class': 'form-control'})
            #if field_name == 'parent_node':
            #    field.widget.attrs.update({'parentid': self.instance.parent_node_id})
